package com.jfs.security.spj;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jfs.entity.Role;
import com.jfs.entity.User;
import com.jfs.exception.ForbiddenException;
import com.jfs.result.ResultCode;
import com.jfs.security.annotations.HasAuthority;
import com.jfs.security.properties.SecurityProperties;
import com.jfs.security.service.RoleService;
import com.jfs.security.service.UserService;
import com.jfs.security.utils.JwtTokenUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Description 权限注解切面 优先级高于日志注解 如果权限注解不足则会不会执行到日志切面
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/8/9
 */
@Aspect
@Component
@Order(0)
@Slf4j
@AllArgsConstructor
public class HasAuthorityAspect {
    private final SecurityProperties securityProperties;
    private final UserService userService;
    private final RoleService roleService;

    /**
     * 权限校验切面
     * @param joinPoint
     * @param hasAuthority
     */
    @Before("@annotation(hasAuthority)")
    public void process(JoinPoint joinPoint, HasAuthority hasAuthority) {
        //获取当前用户权限
        final String tokenForRequest = JwtTokenUtils.getTokenForRequest();
        //获取用户权限信息
        final User user = this.userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, JwtTokenUtils.getUsernameFromToken(tokenForRequest, securityProperties.getSecret())));
        final Role role = this.roleService.getById(user.getRoleId());
        if (!HasAuthority.HasAuthorityEnum.ReadAndWrite.getValue().equals(role.getAuthority())
                && !role.getAuthority().equals(hasAuthority.value().getValue())) {
            //权限不足
            throw new ForbiddenException(ResultCode.FORBIDDEN.getMessage(),ResultCode.FORBIDDEN.getCode());
        }
    }
}
